package com.penghaisoft.microwms.product.service.impl;

import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.dto.ProCountingDto;
import com.penghaisoft.microwms.common.dto.ProStorageDto;
import com.penghaisoft.microwms.common.dto.ProStorageSnDto;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.dto.TransResult;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.common.service.BaseService;
import com.penghaisoft.microwms.common.wms.model.ProStorageSn;
import com.penghaisoft.microwms.common.wms.model.RawLockLog;
import com.penghaisoft.microwms.product.dao.ProStorageSnMapper;
import com.penghaisoft.microwms.product.service.IProStorageSnService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description 成品库存明细表 service
 * @author luoteng
 * @date 2018年6月6日 下午2:50:00 
 * @version 1.0
 */
@Service("proStorageSnService")
public class ProStorageSnServiceImpl extends BaseService implements IProStorageSnService{
	@Resource
	private ProStorageSnMapper proStorageSnMapper;
	
  /**
   * 新增记录
   * @param baseResource
   * @return
   */
	@Override
	public Resp create(ProStorageSn proStorageSn){
		proStorageSnMapper.create(proStorageSn);
		return success();
	}

  /**
   * 删除记录（逻辑删除）
   * @param baseResource
   * @return
   */
	@Override
	public Resp delete(ProStorageSn proStorageSn){
		proStorageSnMapper.delete(proStorageSn);
		return success();
	}
	
  /**
   * 查询列表
   * @param pager
   * @param baseResource
   * @return
   */
	@Override
	public Pager<ProStorageSn> findListByCondition(int page, int rows,ProStorageSn condition){
	    Pager<ProStorageSn> pager = new Pager<>();
	    pager.setPage(page);
	    pager.setRows(rows);
		condition.preQuery();
		long size = proStorageSnMapper.queryCount(condition);
		List<ProStorageSn> records = new ArrayList<ProStorageSn>();
		if(size > 0){
			records = proStorageSnMapper.queryList(pager,condition);
		}
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}

  /**
   * 查询单条
   * @param id
   * @return
   */
	@Override
	public ProStorageSn findById(String id){
		return proStorageSnMapper.queryById(id);
	}
	
  /**
   * 修改记录
   * @param baseResource
   * @return
   */
	@Override
	public Resp update(ProStorageSn proStorageSn){
		proStorageSnMapper.updateContractNoBySelect(proStorageSn);
		return success();
	}
	
	@Override
	public Pager<ProStorageDto> findStorageListByCondition(int page, int rows,ProStorageDto condition){
	    Pager<ProStorageDto> pager = new Pager<>();
	    pager.setPage(page);
	    pager.setRows(rows);
		long size = proStorageSnMapper.queryStorageListCount(condition);
		List<ProStorageDto> records = new ArrayList<ProStorageDto>();
		if(size > 0){
			records = proStorageSnMapper.queryStorageList(pager,condition);
			
			ProStorageDto total = proStorageSnMapper.queryTotal(condition);
        	pager.setOrder("{\"iventAmount\":\"" + total.getIventAmount() + "\",\"availAmount\":\""
        			+ total.getAvailAmount() + "\",\"lockAmount\":\"" + total.getLockAmount()
        			+ "\",\"iventWeight\":\"" + total.getIventWeight() + "\",\"availWeight\":\""
                	+ total.getAvailWeight() + "\",\"lockWeight\":\"" + total.getLockWeight() + "\"}");
		}
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}

	@Override
	public List<ProStorageSn> queryByAny(ProStorageSn proStorageSn) {
		
		return proStorageSnMapper.queryByAny(proStorageSn);
	}

	@Override
	public List<ProStorageSn> queryLose(ProCountingDto proCountingDto) {
		
		return proStorageSnMapper.queryLose(proCountingDto);
	}
	
	@Override
	public List<ProStorageSn> findProStorageSnByCondition(ProStorageSn proStorageSn) {

		return proStorageSnMapper.queryProStorageSnByCondition(proStorageSn);
	}
	
	@Override
	public List<ProStorageSn> queryProStorageSnByCondition(ProStorageSn proStorageSn) {

		return proStorageSnMapper.queryProStorageSnByCondition2(proStorageSn);
	}

	@Override
	public List<ProStorageSn> queryProStorageSnByCondition1(ProStorageSn proStorageSn) {

		return proStorageSnMapper.queryProStorageSnByCondition3(proStorageSn);
	}

	/**
	 * @Title: updateProStorageSnStatus
	 * @Description: 冻结解冻条码
	 * @date 2018年5月22日 上午11:24:53
	 */
	@Override
	@Transactional
	public Resp updateProStorageSnStatus(List<ProStorageSn> list,
			RawLockLog rawLockLog) {
		ProStorageSn proStorageSn = new ProStorageSn();
		List<Integer> proStorageSnIdList = new ArrayList<Integer>();
		String currentUserName = rawLockLog.getLockBy();
		Date date = new Date();
		for (ProStorageSn tmp : list) {
			proStorageSnIdList.add(tmp.getStorageSnId());

//				ProStorageSn cond = new ProStorageSn();
//				cond.setStorageSnId(tmp.getStorageSnId());
//				// 根据snid（唯一）查询，实际一条sn数据
//				List<ProStorageSn> proStorageSnlist = proStorageSnMapper.queryProStorageSnByCondition(cond);
//				if (proStorageSnlist.size() > 0) {
//					// 冻结解冻日志记录
//					RawLockLog lockLog = new RawLockLog();
//					lockLog.setBarcode(proStorageSnlist.get(0).getBarcode());
//					lockLog.setModel(proStorageSnlist.get(0).getModel());
//					lockLog.setModelDesc(proStorageSnlist.get(0).getModelDesc());
//					lockLog.setWlCode(proStorageSnlist.get(0).getWlCode());
//					lockLog.setLockReason(tmp.getLockReason());
//					lockLog.setLockBy(currentUserName);
//					lockLog.setLockDate(date);
//					lockLog.setLockType(tmp.getBarcodeStatus());
//					lockLog.setGmtCreate(date);
//					lockLog.setCreateBy(currentUserName);
//					lockLog.setActiveFlag("1");
//					rawLockLogMapper.create(lockLog);
//				}

		}
		// rawStorageSnIdList条码集合（一次更新）
		proStorageSn.setProStorageSnIdList(proStorageSnIdList);
		proStorageSn.setLockReason(list.get(0).getLockReason());
		proStorageSn.setLastModifiedBy(currentUserName);
		proStorageSn.setGmtModified(date);
		String status = list.get(0).getBarcodeStatus();
		proStorageSn.setBarcodeStatus(status);
		// 冻结解冻更新状态
		Integer updateCnt = proStorageSnMapper.updateOpenClose(proStorageSn);
		System.out.println("更改数量：" + updateCnt);
		if (updateCnt.intValue() <= 0) {
			throw new RuntimeException("更改条码失败");
		}
		int modiNum = proStorageSn.getProStorageSnIdList().size();
		if (updateCnt.intValue() != modiNum) {
			throw new RuntimeException("更新条码的数量和修改条码的数量不一致！");
		}
		return success();
	}

	@Override
	public Resp updateProStorageSnWl(ProStorageSn proStorageSn) {
		Integer updateCnt = proStorageSnMapper.updateWlByCode(proStorageSn);
		if(updateCnt.intValue() == 1){
			return success();
		}else{
			return fail("更改状态失败");
		}
	}

	@Override
	public Resp updateProStorageSn(ProStorageSn proStorageSn) {
		Integer updateCnt = proStorageSnMapper.updateBySelect(proStorageSn);
		if(updateCnt.intValue() == 1){
			return success();
		}else{
			return fail("更改状态失败");
		}
	}

	@Override
	public TransResult lockScan(ProStorageSnDto proStorageSnDto) {
		TransResult result = new TransResult();
		//Code先置为1SUCCESS
        result.setCode(Constant.SUCCESS);
        ProStorageSn proStorageSn = new ProStorageSn();
        proStorageSn.setBarcode(proStorageSnDto.getBarcode());
        proStorageSn.setActiveFlag("1");
        List<ProStorageSn> list = proStorageSnMapper.queryByAny(proStorageSn);
        Resp resp = isExistBarcode(list);
        if((Constant.FAIL).equals(resp.getCode())){
        	result.setCode(resp.getCode());
        	result.setMsg(resp.getMsg());
		}else{
			if("1".equals(list.get(0).getBarcodeStatus())){
				result.setCode(Constant.FAIL);
	        	result.setMsg("该条码已冻结");
        	}else{
	        	//返回信息
	        	result.setList(list);
	        	result.setMsg("该条码可进行冻结，请确认");
        	}
        }
        return result;
	}

	@Override
	public Resp lockConfirm(ProStorageSnDto proStorageSnDto) {
		Resp result = new Resp();
		//Code先置为1SUCCESS
        result.setCode(Constant.SUCCESS);
        ProStorageSn proStorageSn = new ProStorageSn();
        proStorageSn.setBarcode(proStorageSnDto.getBarcode());
        proStorageSn.setActiveFlag("1");
        List<ProStorageSn> list = proStorageSnMapper.queryByAny(proStorageSn);
        Resp resp = isExistBarcode(list);
        if((Constant.FAIL).equals(resp.getCode())){
        	result.setCode(resp.getCode());
        	result.setMsg(resp.getMsg());
		}else{
			if("1".equals(list.get(0).getBarcodeStatus())){
				result.setCode(Constant.FAIL);
	        	result.setMsg("该条码已冻结");
        	}else{
        		//开始冻结
    			proStorageSn.setStorageSnId(list.get(0).getStorageSnId());
    			proStorageSn.setBarcodeStatus("1");//冻结
    			proStorageSn.setLockReason(proStorageSnDto.getLockReason());//0手工冻结1质量冻结
    			proStorageSn.setLastModifiedBy(proStorageSnDto.getLoginName());
    			proStorageSn.setGmtModified(new Date());
    			resp = updateProStorageSn(proStorageSn);
    			if(resp.getCode().equals(Constant.FAIL)){
    				result.setCode(resp.getCode());
    				result.setMsg(resp.getMsg());	
    			}
        	}
        }
        return result;
	}
	
	@Override
	public TransResult moveScan(ProStorageSnDto proStorageSnDto) {
		TransResult result = new TransResult();
		// Code先置为1SUCCESS
		result.setCode(Constant.SUCCESS);
		ProStorageSn proStorageSn = new ProStorageSn();
		proStorageSn.setBarcode(proStorageSnDto.getBarcode());
		proStorageSn.setActiveFlag("1");
		List<ProStorageSn> list = proStorageSnMapper.queryByAny(proStorageSn);
		Resp resp = isExistBarcode(list);
        if((Constant.FAIL).equals(resp.getCode())){
        	result.setCode(resp.getCode());
        	result.setMsg(resp.getMsg());
		}else{
			// 返回信息
			result.setList(list);
			result.setMsg("该条码可进行移库，请选择库位");
		}
        return result;
	}

	@Override
	public Resp moveConfirm(ProStorageSnDto proStorageSnDto) {
		Resp result = new Resp();
		//Code先置为1SUCCESS
        result.setCode(Constant.SUCCESS);
        ProStorageSn proStorageSn = new ProStorageSn();
        proStorageSn.setBarcode(proStorageSnDto.getBarcode());
        proStorageSn.setActiveFlag("1");
        //根据条码查询
        List<ProStorageSn> list = proStorageSnMapper.queryByAny(proStorageSn);
        Resp resp = isExistBarcode(list);
        if((Constant.FAIL).equals(resp.getCode())){
        	result.setCode(resp.getCode());
        	result.setMsg(resp.getMsg());
		}else{
//				if(list.get(0).getWlCode().equals(proStorageSnDto.getWlCode())){
//        			result.setMsg("请重新选择库位，新库位与原库位一致！");
//                	result.setCode(Constant.FAIL);
//        		}
			if(proStorageSnDto.getWaCode().equals(list.get(0).getWaCode())){
    			result.setMsg("请重新选择库区，新库区与原库区一致！");
            	result.setCode(Constant.FAIL);
    		}else{
    			//开始移库
    			proStorageSn.setWaCode(proStorageSnDto.getWaCode());
    			proStorageSn.setWlCode(proStorageSnDto.getWlCode());
    			proStorageSn.setLastModifiedBy(proStorageSnDto.getLoginName());
    			proStorageSn.setGmtModified(new Date());
    			resp = updateProStorageSnWl(proStorageSn);
    			if((Constant.FAIL).equals(resp.getCode())){
    	        	result.setCode(resp.getCode());
    	        	result.setMsg(resp.getMsg());
    			}
    		}
        }
        return result;
	}
	
	/** 
	* @Title: isExistBarcode 
	* @Description: 条码是否在库中
	* @author yanggm 
	* @date 2018年9月27日
	*/
	public Resp isExistBarcode(List<ProStorageSn> list){
		if(list.size() <= 0){
        	return fail("该条码未入库");
        }else{
        	if("2".equals(list.get(0).getBarcodeStatus())){
        		return fail("该条码已出库");
        	}
        }
		return success();
	}

}
